package com.cskaoyan.controller.wx;


import com.cskaoyan.bean.BaseRespVo;
import com.cskaoyan.bean.pojo.MarketUser;
import com.cskaoyan.bean.vo.AuthIndexVO;
import com.cskaoyan.bean.bo.AuthLoginBO;
import com.cskaoyan.bean.vo.AuthLoginVO;
import com.cskaoyan.bean.vo.HomeIndexVO;
import com.cskaoyan.service.UserIndexService;
import com.cskaoyan.service.WxGoodsService;
import com.cskaoyan.shiro.MallToken;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.session.SessionAutoConfiguration;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.Serializable;

/**
 * @description 小程序端User + 首页 index
 * @date        2022.04.08 16:56
 * @package     com.cskaoyan.controller.wx
 * @Classname   UserIndexController
 * @author      rebaogu
 */
@RestController
@RequestMapping("wx")
public class UserIndexController {

    @Autowired
    UserIndexService userIndexService;

    @Autowired
    WxGoodsService wxGoodsService;

    // 登录
    @PostMapping("auth/login")
    public BaseRespVo authLogin(@RequestBody AuthLoginBO authLoginBO) {
        String username = authLoginBO.getUsername();
        String password = authLoginBO.getPassword();
        MallToken wxToken = new MallToken(username, password, "wx");

        Subject subject = SecurityUtils.getSubject();
        subject.login(wxToken);


        AuthLoginVO authLoginVO = userIndexService.authLogin(authLoginBO);
        Serializable id = subject.getSession().getId();
        authLoginVO.setToken((String)id);
        return BaseRespVo.ok(authLoginVO);
    }

    // 登出
    @RequestMapping("auth/logout")
    public BaseRespVo authLogout() {
        Subject subject = SecurityUtils.getSubject();
        subject.logout();
        return BaseRespVo.ok();
    }


    // todo 实现  未登录,返回请登录信息
    // 点击个人用户
    @RequestMapping("user/index")
    public BaseRespVo authIndex() {
        Subject subject = SecurityUtils.getSubject();
        MarketUser marketUser = (MarketUser) subject.getPrincipal();

        return BaseRespVo.ok(userIndexService.authIndex(marketUser));

    }

    // 显示所有商品
    @RequestMapping("home/index")
    public BaseRespVo homeIndex() {
        HomeIndexVO homeIndexVO = wxGoodsService.homeIndex();
        return BaseRespVo.ok(homeIndexVO);
    }

}
